package enumandlambda;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2022-12-11-17:34
 */
public class SemaphoreDemo1 {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(5);
        //创建信号量
        Semaphore semaphore = new Semaphore(2);
        //统一任务的定义
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Thread currThread = Thread.currentThread();
                System.out.println("进入线程："+ currThread.getName());
                try {//获得令牌
                    semaphore.acquire();//如果没有令牌，线程会阻塞在这里
                    System.out.println(currThread.getName()+
                            "：得到令牌 | time :"+ LocalDateTime.now());
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }finally {
                    System.out.println(currThread.getName()+
                            "：释放令牌 | time :"+ LocalDateTime.now());
                    //释放令牌
                    semaphore.release();
                }
            }
        };

        //定义线程执行任务
        service.submit(runnable);
        //定义线程执行任务
        service.submit(runnable);
        //定义线程执行任务
        service.submit(runnable);
        //定义线程执行任务
        service.submit(runnable);
        //定义线程执行任务
        service.submit(runnable);

    }
}
